#include "BH1750.h"

bool BH1750_WriteRegister(uint8_t address)
{
    uint8_t buffer[1] = {address};
	WifiIotI2cData I2cData = {0};
    I2cData.sendBuf = buffer;
    I2cData.sendLen = 1;
    if(I2cWrite(WIFI_IOT_GPIO_IDX_1, (BH1750_DEVICE_ADDRESS << 1) | 0x00, &I2cData) == 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool BH1750_PowerOn(void)
{
    return BH1750_WriteRegister(BH1750_POWER_ON);
}

bool BH1750_PowerOff(void)
{
	return BH1750_WriteRegister(BH1750_POWER_OFF);
}

bool BH1750_Reset(void)
{
	return BH1750_WriteRegister(BH1750_MODULE_RESET);
}

bool BH1750_SetModule(void)
{
	return BH1750_WriteRegister(BH1750_CONTINUE_MODE);
}

bool BH1750_Init(void)
{
    GpioInit();
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_0, WIFI_IOT_IO_FUNC_GPIO_0_I2C1_SDA);
    IoSetFunc(WIFI_IOT_IO_NAME_GPIO_1, WIFI_IOT_IO_FUNC_GPIO_1_I2C1_SCL);
    I2cInit(WIFI_IOT_GPIO_IDX_1, 400000);
    if(BH1750_PowerOff() == false)
	{
		return false;
	}
	else if(BH1750_PowerOn() == false)
	{
		return false;
	}
	else if(BH1750_Reset() == false)
	{
		return false;
	}
	else if(BH1750_SetModule() == false)
	{
		return false;
	}
	else
	{
		return true;
	}
}

bool BH1750_GetData(float *lightIntensity)
{
    uint8_t buffer[2];
	WifiIotI2cData I2cData = {0};
    I2cData.receiveBuf = buffer;
    I2cData.receiveLen = 2;
    if(I2cRead(WIFI_IOT_GPIO_IDX_1, (BH1750_DEVICE_ADDRESS << 1) | 0x01, &I2cData) == 0)
    {
        uint16_t data = ((uint16_t)buffer[0] << 8) + buffer[1];
        *lightIntensity = (float)data / 1.2 * RESOLURTION;
        return true;
    }
    else
    {
        *lightIntensity = 0;
        return false;
    }
}
